from __future__ import division
import datetime
import userConfig
from MongoBetTool.MongoBet import MongoBet
import time
from MailTool.Mail import Mail
import json
from LoggingTool.Logging import Logging


class Balance(object):
    def __init__(self):
        self.mongo = MongoBet()
        self.balance = self.mongo.queryBalance(userConfig.MONGO_TABLE_BALANCE)

    #更新目标值
    def updateBalance(self):
        start_date = datetime.datetime.strptime(self.balance['start_date'], '%Y-%m-%d %H:%M:%S')
        now_date = datetime.datetime.now()
        week_num = ((now_date - start_date).days) // 7 + 1
        if week_num == self.balance['week_num']: return

        self.balance['week_num'] = week_num
        for (times, data) in self.balance['cash'].items():
            if type(data) == type({}):
                data['original'] = data['now']
                data['target'] = data['original'] * (1+data['increase'])
        self.mongo.updateBalance(userConfig.MONGO_TABLE_BALANCE, self.balance)
        Mail.send('更新balance', json.dumps(self.balance, ensure_ascii=False))

    #赢
    def win(self, times):
        data = self.balance['cash'][times]
        data['now'] += (data['original']*data['ratio']*(float(times)-1))
        self.mongo.updateBalance(userConfig.MONGO_TABLE_BALANCE, self.balance)
        Logging.info('赢了且更新数据库, {}'.format(self.balance))

    #输
    def lose(self, times):
        data = self.balance['cash'][times]
        data['now'] -= (data['original'] * data['ratio'])
        self.mongo.updateBalance(userConfig.MONGO_TABLE_BALANCE, self.balance)
        Logging.info('输了且更新数据库, {}'.format(self.balance))

    #获取下注金
    def get(self, times):
        data = self.balance['cash'][times]
        Logging.info('获取下注金, {}'.format(data['original'] * data['ratio']))
        return data['original'] * data['ratio']

    #判断赔率所对应的目标值是否达到
    def isTargetAchieved(self, times):
        data = self.balance['cash'][times]
        return data['now'] >= data['target']



if __name__ == '__main__':

    # d1 = datetime.datetime(2017, 11, 29, 16, 0,0)
    d1 = datetime.datetime.strptime('2017-11-27 00:00:00', '%Y-%m-%d %H:%M:%S')
    # d2 = datetime.datetime.now()
    d2 = datetime.datetime.strptime('2019-12-4 00:00:00', '%Y-%m-%d %H:%M:%S')
    ratio = 0.03
    startCash = 1000
    # print(d2-d1)

    day = (d2-d1).days//7 + 1

    print(day)
    # print('{}%'.format(pow((1+ratio),day)*100-100))
    # print(1000 * pow((1+ratio),day))

